<template>
  <doc-alert title="绘本管理" url="https://doc.iocoder.cn" />

  <ContentWrap>
    <!-- 搜索 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="绘本标题" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入绘本标题或作者"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select
          v-model="queryParams.categoryId"
          placeholder="请选择分类"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="category in categoryList"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" />重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
        >
          <Icon icon="ep:plus" /> 新增
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="checkedIds.length === 0"
          @click="handleDeleteBatch"
        >
          <Icon icon="ep:delete" />批量删除
        </el-button>
        <el-button
          type="success"
          plain
          @click="openCategoryDialog"
        >
          <Icon icon="ep:collection" />分类管理
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table v-loading="loading" :data="list" @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="封面" align="center" width="80">
        <template #default="scope">
          <el-image
            :src="scope.row.coverUrl"
            :preview-src-list="[scope.row.coverUrl]"
            class="w-50px h-50px"
            fit="cover"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column
        label="绘本标题"
        align="center"
        prop="title"
        :show-overflow-tooltip="true"
        min-width="150"
      />
      <el-table-column
        label="作者"
        align="center"
        prop="author"
        :show-overflow-tooltip="true"
        width="120"
      />
      <el-table-column
        label="分类"
        align="center"
        width="100"
      >
        <template #default="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column label="页数" align="center" prop="pageCount" width="80" />
      <el-table-column label="状态" align="center" width="80">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="操作" align="center" width="160">
        <template #default="scope">
          <div class="flex items-center justify-center">
            <el-button
              type="primary"
              link
              @click="openForm('update', scope.row.id)"
            >
              <Icon icon="ep:edit" />修改
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(scope.row.id)"
            >
              <Icon icon="ep:delete" />删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BookForm ref="formRef" @success="getList" />
  
  <!-- 分类管理弹窗 -->
  <CategoryDialog ref="categoryDialogRef" />
</template>

<script setup lang="ts">
import { getBookPage, deleteBook, deleteBookBatch, getBookCategories, type BookVO } from '@/api/miniprogram/book'
import BookForm from './BookForm.vue'
import CategoryDialog from './CategoryDialog.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'

/** 绘本管理 */
defineOptions({ name: 'MiniprogramBook' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<BookVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  keyword: '',
  categoryId: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const checkedIds = ref<number[]>([]) // 选中的ID数组
const categoryList = ref<any[]>([]) // 分类列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getBookPage(queryParams)
    list.value = data.records
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteBook(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除按钮操作 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteBookBatch(checkedIds.value)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    checkedIds.value = []
  } catch {}
}

/** 表格选择事件 */
const handleRowCheckboxChange = (selection: BookVO[]) => {
  checkedIds.value = selection.map(item => item.id!)
}

/** 分类管理 */
const categoryDialogRef = ref()
const openCategoryDialog = () => {
  categoryDialogRef.value.open()
}

/** 获取分类列表 */
const getCategoryList = async () => {
  try {
    const data = await getBookCategories()
    categoryList.value = data
  } catch {}
}

/** 根据分类ID获取分类名称 */
const getCategoryName = (categoryId: number) => {
  const category = categoryList.value.find(item => item.id === categoryId)
  return category ? category.name : '-'
}

/** 初始化 **/
onMounted(() => {
  getList()
  getCategoryList()
})
</script>